<?php

namespace app\common\logic;

use app\common\library\exception\ApiException;
use app\common\model\Bill;
use app\common\model\BillTitle;
use think\Db;
use think\db\Query;
use think\Exception;

class BillTitleLogic extends BaseLogic
{
    public $model;

    public $resourceHandle;

    public function assignModel()
    {
        $this->model          = new BillTitle();
    }

    public function handleSearch(Query $query, array $params): Query
    {
        if (isset($params['id'])) {
            $query->where('id', $params['id']);
        }

        if (isset($params['member_id'])) {
            $query->where('member_id', $params['member_id']);
        }
        return $query;
    }

    /**
     * 列表
     * @param array $params
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function index(array $params)
    {
        $params['field'] = "id,buyerName,buyerTaxNum,email,mobile,type,default";
        $params['orderBy'] = 'default';
        $params['orderType'] = 'desc';
        return $this->getPageList($params);
    }


    /**
     * 列表
     * @param array $params
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function info(array $params)
    {
        return BillTitle::where(['member_id'=>$params['member_id'],'id'=>$params['id']])->find();
    }

    /**
     * 编辑
     * @param array $params
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function edit(array $params)
    {
        Db::startTrans();
        try{
            if ($params['type'] == 1){//企业
                if (!isset($params['buyerTaxNum']) || empty($params['buyerTaxNum']))
                    throw new Exception('纳税人识别码不能为空');
                if (strlen($params['buyerTaxNum']) < 6 || strlen($params['buyerTaxNum']) > 20)
                    throw new Exception('纳税人识别号只支持6-20位');
            }
            if (isset($params['id']) && !empty($params['id'])){ //修改
                $info = BillTitle::where(['id'=>$params['id']])->find();
                if (empty($info))
                    throw new Exception('所更改的发票抬头信息不存在');
                if ($info->member_id != $params['member_id'])
                    throw new Exception('编辑失败，该发票抬头信息不是在你名下');
                if ($info->default != $params['default']){
                    if ($params['default'] == 1){
                        BillTitle::update(['default'=>0],['member_id'=>$params['member_id'],'id'=>['neq',$params['id']]]);
                    }else{
                        throw new Exception('编辑失败，取消默认前，需要先指定另一个发票抬头为默认');
                    }
                }
                $info->buyerName = $params['buyerName'] ?? '';
                $info->buyerTaxNum = $params['buyerTaxNum'] ?? '';
                $info->email = $params['email'] ?? '';
                $info->mobile = $params['mobile'] ?? '';
                $info->type = $params['type'] ?? '';
                $info->openBlank = $params['openBlank'] ?? '';
                $info->buyerAccount = $params['buyerAccount'] ?? '';
                $info->buyerAddress = $params['buyerAddress'] ?? '';
                $info->buyerTel = $params['buyerTel'] ?? '';
                $info->default = $params['default'] ?? 0;
                $info->save();
            }else{
                $info = BillTitle::create([
                    'buyerName'=>$params['buyerName'] ?? '',
                    'buyerTaxNum'=>$params['buyerTaxNum'] ?? '',
                    'email'=>$params['email'] ?? '',
                    'mobile'=>$params['mobile'] ?? '',
                    'type'=>$params['type'] ?? '',
                    'openBlank'=>$params['openBlank'] ?? '',
                    'buyerAccount'=>$params['buyerAccount'] ?? '',
                    'buyerAddress'=>$params['buyerAddress'] ?? '',
                    'buyerTel'=>$params['buyerTel'] ?? '',
                    'member_id'=>$params['member_id'] ?? '',
                    'createtime'=>date('Y-m-d H:i:s'),
                    'default'=>$params['default'] ?? 0,
                ]);
                if ($params['default'] == 1) {
                    BillTitle::update(['default' => 0], ['member_id' => $params['member_id'], 'id' => ['neq', $info->id]]);
                } else {
                    //先查看下名下还有无其他模板
                    $res = BillTitle::get(['member_id'=>$params['member_id'],'default' => 1]);
                    if (empty($res)){
                        $info->default = 1;
                        $info->save();
                    }
                }
            }
            Db::commit();
            return [];
        }catch (Exception $e){
            Db::rollback();
            throw new ApiException($e->getMessage());
        }
    }


    /**
     * 删除
     * @param array $params
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function del(array $params)
    {
        Db::startTrans();
        try{
            $info = BillTitle::where(['member_id'=>$params['member_id'],'id'=>$params['id']])->find();
            if (empty($info))
                throw new Exception('要删除的发票抬头信息不存在');
            if ($info->default == 1){//如果是默认抬头需要指定其他抬头为默认
                $orther_info = BillTitle::where(['member_id'=>$params['member_id'],'id'=>['neq',$params['id']]])->find();
                if (!empty($orther_info)){
                    $orther_info->default =1;
                    $orther_info->save();
                }
            }
            $info->delete();
            Db::commit();
            return [];
        }catch (Exception $e){
            Db::rollback();
            throw new ApiException($e->getMessage());
        }
    }



}